package com.amat0urheu.service.cloudService.impl;

import com.amat0urheu.dao.CloudMapper;
import com.amat0urheu.dao.NetWrokMapper;
import com.amat0urheu.pojo.CloudPojo.NetWork;
import com.amat0urheu.pojo.CloudPojo.OpenStack;
import com.amat0urheu.pojo.ReturnRes;

import com.amat0urheu.service.cloudService.NetWorkService;
import com.amat0urheu.utils.CloudUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class NetWorkServiceImpl implements NetWorkService {
    @Autowired
    CloudMapper cloudMapper;
    @Autowired
    NetWrokMapper netWrokMapper;


    @Override
    public ReturnRes getAllNetWorks(String openstackIP,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<NetWork> networkList = netWrokMapper.getAllNetworks(openstackIP);
        if (networkList != null) {
            return new ReturnRes(true, new PageInfo<>(networkList), "查询成功");
        }
        return new ReturnRes(false, "查询失败");
    }

    @Override
    public void refreshNetwork(String openstackIP) {
        try {
            List<NetWork> networks= CloudUtils.getNetWorks(cloudMapper.getOpenstackByopenstackIP(openstackIP));
            netWrokMapper.dropNetworks( openstackIP);
            netWrokMapper.insertnewAllNetwork(networks);
        }catch (Exception e){
            System.out.println("系统故障");
        }


    }



    @Override
    public ReturnRes createNetwork(NetWork netWork) {
        try {
            OpenStack openStack= cloudMapper.findOpenstackByIp(netWork.getOpenstackIP());
            List<OpenStack> openStacks=new ArrayList<>();
            openStacks.add(openStack);
            NetWork network2= CloudUtils.CreateNetWork(openStacks,netWork);
            netWrokMapper.insertNetwork(network2);
            return new ReturnRes(true, network2, String.format("%s 添加成功", network2.getName()));
        }catch (Exception e){
            return new ReturnRes(false,"添加失败,请输入正确的参数");
//            return new ReturnRes(false,  String.format("%s 添加失败,请输入合理参数" ));
        }

    }

    @Override
    public ReturnRes removeNetWork(NetWork netWork) {

        OpenStack openStack= cloudMapper.findOpenstackByIp(netWork.getOpenstackIP());
        List<OpenStack> openStacks=new ArrayList<>();
        openStacks.add(openStack);
        if(    CloudUtils.DleteNetWork(openStacks,netWork.getNetWorkId())&&netWrokMapper.deleteNetWorkBynetWorkId(netWork.getNetWorkId())==1){
            return new ReturnRes(true, "操作成功");
        }
        return new ReturnRes(false, "操作失败,可能此网路中有资源或者已经不存在");
    }


}
